#include "ShareMemory.h"
// initialize static members
int ShareMemory::sm_counter = 0;
int ShareMemory::sm_size = 0;
int* ShareMemory::sm_data = 0;
ShareMemory::ShareMemory(int sz) {
  if (sz <= 0) {
    cout << "size <= 0" << endl;
    return;
  }
  if (sm_counter == 0) {
    cout << "first object created" << endl;
    sm_size = sz;
    sm_data = new int[sz];
    if (sm_data == 0) {
      cout << "memory allocation " << sz << "fail" << endl;
      return;
    }
  }
  if (sm_size >= sz) {
    // do nothing
  } else {
    // allocate more space, copy elements
    int * newdata = new int[sz];
    if (newdata == 0) {
      cout << "memory allocation " << sz << "fail" << endl;
      return;
    }
    for (int indexcnt = 0; indexcnt < sm_size; indexcnt ++) {
      newdata[indexcnt] = sm_data[indexcnt];
    }
    delete [] sm_data;
    sm_data = newdata;
    sm_size = sz;
  }

  sm_counter ++;
}

ShareMemory::ShareMemory(const ShareMemory & orig) {
  sm_counter ++;
  // no need to do anything else
}

ShareMemory& ShareMemory::operator = (const ShareMemory & orig) {
  // nothing needs to be done
  return * this;
}

bool ShareMemory::checkIndex(int index) const {
  if ((index < 0) || (index >= sm_size)) {
    cout << "index out of range" << endl;
    return false;
  }
  return true;
}

int ShareMemory::read(int index) const {
  if (checkIndex(index)) {
    return sm_data[index];
  } else {
    return -1;
  }
}

void ShareMemory::write(int index, int value) {
  if (checkIndex(index)) {
    sm_data[index] = value;
  }
}

ShareMemory::~ShareMemory() {
  sm_counter --;
  if (sm_counter == 0) {
    cout << "no more object" << endl;
    delete [] sm_data;
  }
}
